﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace M3U8下载神器
{
    public class TsDownloader
    {
        public int Try { set; get; } = 5;
        string Gid { set; get; }
        public TsDownloader(string gid)
        {
            Gid = gid;
        }
        public bool Download(WebClient httpClient, M3U8Package.TsInfo ts,out string exception)
        {
            exception = "";
            for (int i = 0; i < Try && !ts.Finish; i++)
            {
                try
                {
                    var temp = Gid + "/" + ts.Id +"-"+new Random().Next()+ ".ts.tmp";
                    var dest = Gid + "/" + ts.Id + ".ts";
                    httpClient.DownloadFile(ts.Path,temp );
                    FileInfo fi = new FileInfo(temp);
                    if(ts.Method== "AES-128")
                    {
                        var key = ts.Key;
                        var iv = ts.Iv ?? "0000000000000000";
                        AESDecrypt(temp, key, iv, dest);
                        fi.Delete();
                    }
                    else
                    {
                        fi.MoveTo(dest);
                    }
                    ts.Finish = true;
                }
                catch (Exception e)
                {
                    exception = e.Message;
                }
            }
            return ts.Finish;
        }
        private static void AESDecrypt(string srcFile, string Key, string Vector, string destFile)
        {
            byte[] bKey = new byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
            byte[] bVector = new byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
            Rijndael Aes = Rijndael.Create();
            using (FileStream src = new FileStream(srcFile, FileMode.Open))
            {
                //把内存流对象包装成加密对象
                using (CryptoStream ds = new CryptoStream(src, Aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read))
                {
                    //明文存储区
                    using (FileStream dest = new FileStream(destFile, FileMode.Create))
                    {
                        ds.CopyTo(dest);
                    }
                }
            }
        }
    }
}
